import logging
import sys
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

import django
from django import http
from django import shortcuts

from datetime import datetime
from urllib import quote

from favicon.models import Favicon, FaviconURI, Client, Access, CountStat, DateCountStat
from favicon.helpers import *

def image(request, id):
  mimetype = "image/png"
  favicon = Favicon.get_by_key_name(id)
  if favicon.mimetype: mimetype = favicon.mimetype
  return http.HttpResponse(favicon.favicon_bytes, mimetype=mimetype)

def receiver(request):
  params = {}
#  logging.debug("file contents: " + str(request.FILES))

  try:
    if (len(request.FILES['favicon']['content']) > 51200):
      logging.error("someone posted a favicon thats over 50kB (most are < 1kB), no thank you!")
      return

    # hack, key_name cannot begin with a digit
    md5 = md5_key(request.POST['faviconMD5'][:32])
    f = Favicon.get_or_insert(md5, 
                mimetype = request.FILES['favicon']['content-type'],
                favicon_bytes = request.FILES['favicon']['content'])

    # inc total_favicons
    if not f.accesses:
      inc_total_favicons()
      inc_today_favicons()

    f.accesses += 1
    f.put()

    inc_total_accesses()
    inc_today_accesses()

    fu = None
    if request.POST.has_key('faviconURI'):
      fu = FaviconURI(key_name = request.POST['faviconURI'],
                      uri = request.POST['faviconURI'],
                      favicon = f)
      fu.put()

    c = None
    if request.POST.has_key('clientID'):
      c = Client(key_name = request.POST['clientID'],
                client_id = request.POST['clientID'])
      c.put()

    a = Access(favicon=f, favicon_uri=fu, client=c)
    a.put()
  except:
    logging.error("Unexpected error: " + str(sys.exc_info()))
    logging.error(request.FILES)

  return shortcuts.render_to_response('index.html', params)
  
def contrib(request):
  params = {}
  return shortcuts.render_to_response('contrib.html', params)

def toggle_active(request, id):
  favicon = Favicon.get_by_key_name(id)
  favicon.active = not favicon.active
  favicon.put()
  return http.HttpResponseRedirect("/toggler/")

def toggler(request):
  params = {}
  favicons = Favicon.all().filter('active = ', True)
  good_keys = [ f.key().id_or_name() for f in favicons ]
  params['favicons_active'] = good_keys

  favicons = Favicon.all().filter('active = ', False)
  bad_keys = [ f.key().id_or_name() for f in favicons ]
  params['favicons_disabled'] = bad_keys

  return shortcuts.render_to_response('toggler.html', params)


# TODO: implement charts for data
def get_sparkline(data):
  # first stab, not working 
  max_val = float(max(data))
  vals = [ str( (d / max_val)*100 ) for d in data ]
  data_string = ",".join(data)
  img_string = "http://chart.apis.google.com/chart?chs=100x20&cht=ls&chco=0077CC&chm=B,E6F2FA,0,0,0&chls=1,0,0&chd=t:%s" % (data_string)
  return img_string

def top_x(request):
  params = {}
  params['most_recently_created'] = [ f.key().id_or_name() for f in most_recently_added(10) ]
  params['most_recently_accessed'] = [ f.favicon.key().id_or_name() for f in most_recently_accessed(10) ]
  params['most_accessed'] = [ f.key().id_or_name() for f in most_accessed(10) ]
  params['favicon_cnt'] = get_total_favicons()
  params['favicon_today_cnt'] = get_today_favicons()
  params['accesses_today_cnt'] = get_today_accesses()
  return shortcuts.render_to_response('top.html', params)

def index(request):
  params = {}
  params['favicon_cnt'] = get_total_favicons()
  params['accesses_cnt'] = get_total_accesses()
  params['favicon_today_cnt'] = get_today_favicons()
  params['accesses_today_cnt'] = get_today_accesses()
  return shortcuts.render_to_response('gears.html', params)

def update(request):
  inc_today_updates()
  return http.HttpResponseRedirect('/update/update.rdf')

def api(request, year, month, day, hour, min, sec, micro):
  params = {}
  dt = datetime(int(year), int(month), int(day), int(hour), int(min), int(sec), int(micro))
  favicons = Favicon.all().filter('active = ', True).filter('created_at > ', dt).order('created_at').fetch(1000)
  if not favicons:
    params['favicons'] = []
    params['next_url'] = datetime_url(dt)
    return shortcuts.render_to_response('api.html', params)
    
  keys = [ quote(f.key().id_or_name()) for f in favicons ]
  next_url = datetime_url(favicons[-1].created_at)

  params['favicons'] = keys
  params['next_url'] = next_url
  return shortcuts.render_to_response('api.html', params)
